package com.jade.web.controller.system;

import com.jade.common.annotation.Log;
import com.jade.common.constant.UserConstants;
import com.jade.common.core.controller.BaseController;
import com.jade.common.core.domain.AjaxResult;
import com.jade.common.core.domain.Ztree;
import com.jade.common.enums.BusinessType;
import com.jade.framework.util.ShiroUtils;
import com.jade.system.domain.SysMenu;
import com.jade.system.domain.SysRole;
import com.jade.system.domain.SysUser;
import com.jade.system.service.ISysMenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 * 
 * @author jade
 */
@Controller
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController
{
    private String prefix = "system/menu";

    @Autowired
    private ISysMenuService menuService;

    @RequiresPermissions("system:menu:view")
    @GetMapping()
    public String menu()
    {
        return prefix + "/menu";
    }

    @RequiresPermissions("system:menu:list")
    @PostMapping("/list")
    @ResponseBody
    public List<SysMenu> list(SysMenu menu)
    {
        Long userId = ShiroUtils.getUserId();
        List<SysMenu> menuList = menuService.selectMenuList(menu, userId);
        return menuList;
    }

    /**
     * 删除菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:menu:remove")
    @GetMapping("/remove/{menuId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.selectCountMenuByParentId(menuId) > 0)
        {
            return AjaxResult.warn("存在子菜单,不允许删除");
        }
        if (menuService.selectCountRoleMenuByMenuId(menuId) > 0)
        {
            return AjaxResult.warn("菜单已分配,不允许删除");
        }
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(menuService.deleteMenuById(menuId));
    }

    /**
     * 新增
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    {
        SysMenu menu = null;
        if (0L != parentId)
        {
            menu = menuService.selectMenuById(parentId);
        }
        else
        {
            menu = new SysMenu();
            menu.setMenuId(0L);
            menu.setMenuName("主目录");
        }
        mmap.put("menu", menu);
        return prefix + "/add";
    }

    /**
     * 新增保存菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:menu:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysMenu menu)
    {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        menu.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @GetMapping("/edit/{menuId}")
    public String edit(@PathVariable("menuId") Long menuId, ModelMap mmap)
    {
        mmap.put("menu", menuService.selectMenuById(menuId));
        return prefix + "/edit";
    }

    /**
     * 修改保存菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:menu:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysMenu menu)
    {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        menu.setUpdateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 选择菜单图标
     */
    @GetMapping("/icon")
    public String icon()
    {
        return prefix + "/icon";
    }

    /**
     * 校验菜单名称
     */
    @PostMapping("/checkMenuNameUnique")
    @ResponseBody
    public String checkMenuNameUnique(SysMenu menu)
    {
        return menuService.checkMenuNameUnique(menu);
    }

    /**
     * 加载角色菜单列表树
     */
    @GetMapping("/roleMenuTreeData")
    @ResponseBody
    public List<Ztree> roleMenuTreeData(SysRole role)
    {
        Long userId = ShiroUtils.getUserId();
        List<Ztree> ztrees = menuService.roleMenuTreeData(role, userId);
        return ztrees;
    }

    /**
     * 加载所有菜单列表树
     */
    @GetMapping("/menuTreeData")
    @ResponseBody
    public List<Ztree> menuTreeData()
    {
        Long userId = ShiroUtils.getUserId();
        List<Ztree> ztrees = menuService.menuTreeData(userId);
        return ztrees;
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree/{menuId}")
    public String selectMenuTree(@PathVariable("menuId") Long menuId, ModelMap mmap)
    {
        mmap.put("menu", menuService.selectMenuById(menuId));
        return prefix + "/tree";
    }
    
    // 获取用户一级菜单
    @GetMapping("/getMenus")
    @ResponseBody
    public List getFirstMenus()
	{   
    	SysUser user = ShiroUtils.getSysUser();
    	String menuId =  getRequest().getParameter("menuId");
    	List<Map> menu = new ArrayList<Map>();
    	if(menuId==null){
    		List<SysMenu> menus = menuService.selectFirstMenusByUser(user);
    		for(int i=0;i<menus.size();i++){
        		SysMenu sysMenu = menus.get(i);
        		Map map = new HashMap();
        		map.put("menuGuid", sysMenu.getMenuId());
        		if("C".equals(sysMenu.getMenuType())){
        			map.put("src","/navs");
        			map.put("json",sysMenu.getUrl());
        		}else{
        			map.put("src", "/nav");
        			map.put("json","/getMenus?menuId="+sysMenu.getMenuId());
        		}
        		map.put("title", sysMenu.getMenuName());
        		map.put("cache", false);
        		map.put("selected", false);
        		if(i==0)
        			map.put("selected", true);
        		map.put("state", "null");
        		map.put("iconCls",sysMenu.getIcon());
        		
        		menu.add(map);
        	}
    	}else{
    		List<Long> menuIds = new ArrayList<Long>();
    		menuIds.add(Long.valueOf(menuId));
    		List<SysMenu> menus = menuService.selectSonMenusByUser_Menu(user,menuIds);
    		menuIds.clear();
    		for(int i=0;i<menus.size();i++){
    			menuIds.add(menus.get(i).getMenuId());
    		}
    		List<SysMenu> sysMenus = menuService.selectSonMenusByUser_Menu(user, menuIds);
    		Map<Long,List> sonMenu =  new HashMap();
    		SysMenu sysMenu;
    		for(int i=0;i<sysMenus.size();i++){
    			sysMenu = sysMenus.get(i);
    			if(sonMenu.get(sysMenu.getParentId()) == null) sonMenu.put(sysMenu.getParentId(), new ArrayList<Map>());
    			Map sonMap = new HashMap();
    			sonMap.put("id", sysMenu.getMenuId());
				sonMap.put("parentId", sysMenu.getParentId());
				sonMap.put("url", sysMenu.getUrl());
				sonMap.put("text", "<span class='"+sysMenu.getIcon()+"'></span>&nbsp;"+sysMenu.getMenuName());
				sonMap.put("checked", false);
				sonMap.put("state", null);
				sonMenu.get(sysMenu.getParentId()).add(sonMap);
    		}
    		for(int i=0;i<menus.size();i++){
    			sysMenu = menus.get(i);
    			Map map = new HashMap();
    			map.put("id", sysMenu.getMenuId());
    			map.put("parentId",0);
    			map.put("text", sysMenu.getMenuName());
    			map.put("iconCls", sysMenu.getIcon());
    			map.put("checked", false);
    			if(i==0)
    				map.put("checked", true); 
    			map.put("state", "closed");
    			if(sonMenu.get(sysMenu.getMenuId())!=null){
	    			map.put("children", sonMenu.get(sysMenu.getMenuId()));
    			}else{
    				map.put("url", sysMenu.getUrl());
    				map.put("state", "url");
    			}
    			menu.add(map);
    		}
            
    	}
    	
        return menu;
    }
}